package com.fufan.mtsaas.util;

import com.fufan.mtsaas.modules.newtech.xjstech.bo.request.XjsTechSendSmaRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Component
public class SMSSender {

//    private static final String SMS_API_URL = "http://your-sms-api-url.com/sendMessage"; // 替换为实际的短信接口地址

    @Value("${sms.enable}")
    private Boolean smsEnable;

    @Value("${sms.url}")
    private String smsUrl;

    @Value("${shzy.dburl}")
    private String dbUrl;

    private static final String CHARSET = "GBK";

    @Autowired
    private ParamUtil paramUtil;

    /**
     * 发送短信
     *
     * @param map 包含短信发送参数的请求对象
     */
    public String sendSms(XjsTechSendSmaRequest map) {
        if (!smsEnable) {
            log.info("短信功能未启用，不发送短信");
            return "短信功能未启用，不发送短信";
        }
        String info = "";
        String shortName = paramUtil.getTSysParam("HOSPITAL_NAME");
        if (Objects.nonNull(shortName) && shortName.equalsIgnoreCase("PTZX")) {
            log.info("开始发送短信，请求参数：{}", map);

            String xmlRequest = createXmlRequest(map.getCustomerID(), map.getCustomerName(), map.getCustomerType(), map.getSrvType(), map.getTel(), map.getMessage());
            log.info("生成的XML请求内容：\n{}", xmlRequest);

            info = send(smsUrl, xmlRequest);
            log.info("短信发送完成，返回结果：{}", info);
        } else if (Objects.nonNull(shortName) && shortName.equalsIgnoreCase("SHZY")) {
            log.info("开始发送短信，请求参数：{}", map);

            info = callSHZYMsg(smsUrl, map);
            log.info("短信发送完成，返回结果：{}", info);
        } else {
            info = "未知短信接口";
        }

        return info;
    }

    /**
     * 上海中医短信接口 - 存储过程写入SQLServer表中
     *
     * @param smsUrl
     * @param map
     */
    private String callSHZYMsg(String smsUrl, XjsTechSendSmaRequest map) {
        String ret = "";

        try {
            Connection conn = DriverManager.getConnection(dbUrl);
            if (Objects.nonNull(conn)) {
                String sql = "{call sup_psp_mms_sendmessage(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}"; // 替换为你的存储过程名和参数
                try (CallableStatement cstmt = conn.prepareCall(sql)) {
                    //设置参数值-业务消息编码
                    cstmt.setString(1, "0002.0001.0001.0001");
                    //设置参数值-业务系统编码
                    cstmt.setString(2, "0002.0001.0002.0006");
                    //设置参数值-渠道编号
                    cstmt.setString(3, "0002.0001.0004.0001");
                    //设置参数值-操作员ID
                    cstmt.setString(4, "MTSaas" + map.getSrvType());
                    //设置参数值-操作流水号
                    cstmt.setString(5, String.valueOf(System.currentTimeMillis()));
                    //设置参数值-患者id
                    cstmt.setString(6, map.getCustomerID());
                    //设置参数值-接收者姓名
                    cstmt.setString(7, map.getCustomerName());
                    //设置参数值-联系方式（手机号/wechat等）
                    cstmt.setString(8, map.getTel());
                    //设置参数值-消息内容
                    cstmt.setString(9, map.getMessage());
                    //设置参数值-发送时间
                    cstmt.setString(10, DateUtil.formatDate(new Date(), DateUtil.DATE_TIME_FORMAT));
                    boolean suss = cstmt.execute(); // 执行存储过程
                    ret = "sup_psp_mms_sendmessage调用成功";
                }
            }
        } catch (SQLException e) {
            ret = "callSHZYMsg exception: " + e.getLocalizedMessage();
            log.error(ret);
            e.printStackTrace();
        }

        return ret;
    }


    /**
     * @param url
     * @param xmlRequest
     * @param smsMethod
     * @return
     */
    public static String send(String url, String xmlRequest, String smsMethod) {

        int responseCode = 0;
        String result = "";
        try {
            String requestUrl = url;
            HttpPost post = new HttpPost(requestUrl);
            post.addHeader("Content-Type", "application/json");
            post.setEntity((new StringEntity(xmlRequest, CHARSET)));

            CloseableHttpResponse response = HttpConnPoolUtil.getHttpClient().execute(post);

            responseCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, CHARSET);
            return result;
        } catch (Exception e) {
            log.debug(" 响应码:" + responseCode + ", 响应内容:" + result + ", 请求内容:" + url);
            log.debug(" 异常", e);

            return "异常" + e.getLocalizedMessage();
        }
    }

    /**
     * 发送HTTP POST请求
     *
     * @param smsUrl     短信服务的URL
     * @param xmlRequest XML格式的请求内容
     * @return 服务端返回的结果
     */
    public static String send(String smsUrl, String xmlRequest) {
        try {
            URL url = new URL(smsUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/xml; charset=" + CHARSET);
            conn.setRequestProperty("Content-Length", String.valueOf(xmlRequest.getBytes(CHARSET).length));
            conn.setDoOutput(true);

            try (DataOutputStream dos = new DataOutputStream(conn.getOutputStream())) {
                dos.write(xmlRequest.getBytes(CHARSET));
            } catch (Exception e) {
                log.error("发送短信时发生异常", e);
                return "Error: " + e.getMessage();
            }

            int responseCode = conn.getResponseCode();
            log.info("收到响应，状态码：{}", responseCode);

            StringBuilder response = new StringBuilder();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), CHARSET))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            }

            log.debug("响应内容：\n{}", response.toString());
            return response.toString();
        } catch (IOException e) {
            log.error("发送短信时发生异常", e);
            return "Error: " + e.getMessage();
        }
    }

    /**
     * 创建XML请求内容
     *
     * @param customerID   客户ID
     * @param customerName 客户姓名
     * @param customerType 客户类型
     * @param srvType      服务类型
     * @param tel          手机号码
     * @param message      短信内容
     * @return XML格式的请求内容
     */
    private static String createXmlRequest(String customerID, String customerName, String customerType, String srvType, String tel, String message) {
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tns=\"http://SMS\">\n");
        sb.append("    <soapenv:Header/>\n");
        sb.append("    <soapenv:Body>\n");
        sb.append("        <tns:sendMessage>\n");
        sb.append("            <tns:in0>\n");
        sb.append("                &lt;?xml version='1.0' encoding='gbk'?&gt;\n");
        sb.append("                &lt;SERVICES sname=\"PZX.FSDX\"&gt;\n");
        sb.append("                    &lt;PARAMS&gt;\n");
        sb.append("                        &lt;PARAM pname=\"customerID\" pval=\"" + customerID + "\" /&gt;\n");
        sb.append("                        &lt;PARAM pname=\"customerName\" pval=\"" + customerName + "\" /&gt;\n");
        sb.append("                        &lt;PARAM pname=\"customerType\" pval=\"" + customerType + "\" /&gt;\n");
        sb.append("                        &lt;PARAM pname=\"srvType\" pval=\"" + srvType + "\" /&gt;\n");
        sb.append("                        &lt;PARAM pname=\"tel\" pval=\"" + tel + "\" /&gt;\n");
        sb.append("                        &lt;PARAM pname=\"message\" pval=\"" + message + "\" /&gt;\n");
        sb.append("                    &lt;/PARAMS&gt;\n");
        sb.append("                &lt;/SERVICES&gt;\n");
        sb.append("            </tns:in0>\n");
        sb.append("        </tns:sendMessage>\n");
        sb.append("    </soapenv:Body>\n");
        sb.append("</soapenv:Envelope>");
        return sb.toString();
    }

    // 测试用例
    public static void main(String[] args) {

        String xmlRequest = createXmlRequest("1382", "胡老师", "信息科", "UPS报警", "18827514235", "1333测试短信内容");
        log.debug("生成的XML请求内容：\n{}", xmlRequest);

        String info = send("http://192.168.30.10:8080/WS_PZX_SMS/services/sendMessage", xmlRequest);
        System.out.println("短信发送结果：\n" + info);
    }


    // 根据状态获取短信内容
    // 状态：0-草稿 10-科室负责人初审；20-医务部初审；30-伦理委员会；40-院内组织评审；50-医保办公室；60-财务部，项目开通；70-医务部 （结束）；80-年审下发  80-年审下发；90-科室主任审批；100-医疗技术临床应用管理委员会审批 110: 已完成年审
    public static String getContent(String userName, String techName, Integer status) {
        String content = "";
        switch (status) {
            case 1100:
                // 定制化： 流转中的任意一个结点完成审批后是驳回拒绝的结果
                content = "您的" + techName + "新技术新项目申报已完成审批，可至【OA管理平台”或“医务一网通办平台】进行查看审批结果。";
                break;
            case 1120:
                // 定制化：  最后一个医务部存档的结点。 （暂时不用：1100已经包含了）
                content = "您的" + techName + "新技术新项目申报已完成审批，可至【OA管理平台”或“医务一网通办平台】进行查看审批结果。";
                break;
            case 0:
                content = "您已成功提交" + techName + "新技术新项目申报。";
                break;
            case 10:
                content = "您有一条新技术新项目申报待审批。可至【OA管理平台”或“医务一网通办平台】进行审批。";
                break;
            case 20:
                content = "您有一条新技术新项目申报待审批。可至【OA管理平台”或“医务一网通办平台】进行审批。";
                break;
            case 30:
                content = "您有一条新技术新项目申报待审批。可至【OA管理平台”或“医务一网通办平台】进行审批。";
                break;
            case 40:
                content = "您有一条新技术新项目申报待审批。可至【OA管理平台”或“医务一网通办平台】进行审批。";
                break;
            case 50:
                content = "您有一条新技术新项目申报待审批。可至【OA管理平台”或“医务一网通办平台】进行审批。";
                break;
            case 60:
                content = "您有一条新技术新项目申报待审批。可至【OA管理平台”或“医务一网通办平台】进行审批。";
                break;
            case 70:
                content = userName + "申请的" + techName + "新技术新项目已开通。可至【OA管理平台”或】医务一网通办平台”进行查看。";
                break;
            case 80:
                content = "您的" + techName + "新技术新项目已经可以进行年审操作，可至【OA管理平台”或“医务一网通办平台】进行年审操作。";
                break;
            case 90:
                content = "您有一条新技术新项目年审待审批。可至【OA管理平台”或“医务一网通办平台】进行审批。";
                break;
            case 100:
                content = "您有一条新技术新项目年审待审批。可至【OA管理平台”或“医务一网通办平台】进行审批";
                break;
            case 110:
                content = "您的" + techName + "新技术新项目年审已完成审批，可至【OA管理平台”或“医务一网通办平台】进行查看审批结果。";
                break;
            default:
                content = "未知状态";
        }
        return content;
    }
}